package com.ruoyi.web.controller.energy;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ApproveMission;
import com.ruoyi.common.core.domain.entity.EnergyRecord;
import com.ruoyi.common.core.domain.entity.GarbageRecord;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.EnergyRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.ApproveService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author：liyouxin
 * @date：2023/11/19 21:45
 */
@RestController
@RequestMapping("/energy/record")
public class EnergyRecordController extends BaseController {
	@Resource
	private EnergyRecordMapper energyRecordMapper;

	@Resource
	private SysUserPostMapper sysUserPostMapper;

	@Resource
	private SysUserMapper sysUserMapper;

	@Resource
	private ApproveService approveService;

	@GetMapping("/list")
	public TableDataInfo list(EnergyRecord energyRecord) {
//		Long userId = SecurityUtils.getUserId();
//		SysUser sysUser = sysUserMapper.selectUserById(userId);
//		List<Long> postIds = sysUserPostMapper.getUserPosts(SecurityUtils.getUserId());
//		if (CollectionUtils.isEmpty(postIds)) {
//			// 默认只能看到自己的数据
//			energyRecord.setCreator(userId);
//			energyRecord.setDept(null);
//		} else if (postIds.stream().anyMatch(p -> p < 7)) {
//			// 副主任以上能看到所有数据
//			energyRecord.setCreator(null);
//			energyRecord.setDept(null);
//		} else if (postIds.stream().anyMatch(p -> p <= 8 && p >= 7)) {
//			// 科长副科长只能看到自己科室的数据
//			energyRecord.setCreator(null);
//			energyRecord.setDept(sysUser.getDeptId());
//		} else {
//			// 其他人只能看到自己科室的自己的数据
//			energyRecord.setCreator(userId);
//			energyRecord.setDept(sysUser.getDeptId());
//		}
		startPage();
		List<EnergyRecord> list = energyRecordMapper.selectList(energyRecord);
		fillApprove(list);
		return getDataTable(list);
	}

	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable Long id) {
		return success((energyRecordMapper.selectById(id)));
	}

	@PostMapping("/add")
	public AjaxResult add(@Validated @RequestBody EnergyRecord energyRecord)
	{
		Long userId = SecurityUtils.getUserId();
		energyRecord.setCreator(userId);
		energyRecord.setDept(Optional.ofNullable(sysUserMapper.selectUserById(userId)).map(SysUser::getDeptId).orElse(null));
		energyRecord.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
		int result = energyRecordMapper.insert(energyRecord);
		if (result == 1) {
			ApproveMission approveMission = ApproveMission.builder()
							.applicant(SecurityUtils.getUserId())
							.status("审批中")
							.name("能耗记录审批")
							.activityId(energyRecord.getId())
							.activityType("能耗记录审批").build();
			approveMission.setCreateBy(SecurityUtils.getNickName());
			approveService.createApproveMission(approveMission);
			return success();
		}
		return error();
	}

	@PutMapping
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult edit(@Validated @RequestBody EnergyRecord energyRecord) {
		energyRecord.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
		int result= energyRecordMapper.update(energyRecord);

		EnergyRecord search = energyRecordMapper.selectById(energyRecord.getId());
		if (search == null || !search.getCreateBy().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
			throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法修改");
		}

		if (result == 1) {
			return success();
		}
		return error();
	}

	@DeleteMapping("/{id}")
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult remove(@PathVariable Long id) {
		EnergyRecord search = energyRecordMapper.selectById(id);
		if (search == null || !search.getCreateBy().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
			throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法修改");
		}
		return toAjax(energyRecordMapper.deleteById(id));
	}

	private void fillApprove(List<EnergyRecord> list) {
		if (CollectionUtils.isEmpty(list)) {
			return;
		}
		for (EnergyRecord record : list) {
			ApproveMission approveMission = approveService.getApproveMissionByActivityd(record.getId(), "能耗记录审批");
			if (approveMission == null) {
				record.setApproveStatus("未提交审批");
			} else {
				record.setApproveMissionId(approveMission.getId());
				if ("通过".equals(approveMission.getStatus()) || "拒绝".equals(approveMission.getStatus())) {
					if (record.getUpdateTime() != null && record.getUpdateTime().compareTo(approveMission.getApproveTime()) > 0) {
						record.setApproveStatus("修改未提交审批");
					} else {
						record.setApproveStatus(approveMission.getStatus());
					}
				} else {
					record.setApproveStatus(approveMission.getStatus());
				}
			}
		}
	}
}
